package com.qf.game.application.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.qf.game.application.entity.HappyBeanHistory;
import com.qf.game.application.entity.RechargeOrder;
import com.qf.game.application.service.IHappyBeanHistoryService;
import com.qf.game.application.service.IRechargeOrderService;
import com.qf.game.application.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 充值订单
 */
@RestController
@CrossOrigin
public class RechargeOrderController {

    @Autowired
    private IRechargeOrderService rechargeOrderService;

    @Autowired
    private IHappyBeanHistoryService happyBeanHistoryService;

    @Autowired
    private IUserService userService;

    /**
     * 下单  欢乐豆 ： 充值金额 = 100 ： 1
     */
    @RequestMapping("/order/create")
    public String createOrder(Integer uid, double money){

        String orderid = UUID.randomUUID().toString();

        //double Integer -> BitDecimal
        BigDecimal moneyBD = BigDecimal.valueOf(money);
        BigDecimal numberBD = BigDecimal.valueOf(100);

        //创建订单对象
        RechargeOrder rechargeOrder = new RechargeOrder();
        rechargeOrder.setuId(uid);//下单用户id
        rechargeOrder.setMoney(moneyBD);//下单的金额
        rechargeOrder.setOrderId(orderid);//订单号
        rechargeOrder.setStatus(0);//未支付
        rechargeOrder.setCreateTime(new Date());//下单时间
        rechargeOrder.setBeanNumber(moneyBD.multiply(numberBD).intValue());//充值的欢乐豆数量 money * 100

        //添加订单
        rechargeOrderService.insertOrder(rechargeOrder);

        return orderid;
    }

    /**
     * 查询订单列表 根据用户id
     */
    @RequestMapping("/order/list")
    public List<RechargeOrder> queryList(Integer uid){
        return rechargeOrderService.queryRechargeOrderByUid(uid);
    }

    /**
     * 订单支付的接口
     */
    @RequestMapping("/order/pay")
    public void orderPay(String orderid, HttpServletResponse response) throws IOException {
        System.out.println("接收到支付的订单：" + orderid);

        //通过订单号 查询订单信息
        RechargeOrder order = rechargeOrderService.getByOrderId(orderid);

        //调用支付宝进行支付
        AlipayClient alipayClient =  new DefaultAlipayClient(
                "https://openapi.alipaydev.com/gateway.do",//沙箱环境的地址
                "2016073000127352",//APPID
                "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDqN7oDbnZUY66s48aYzhOVP+KHssz0WFT05kJYHSpWpVWceFflVGkAoHCZE00PbVcvZMAaYwzFzVCT9A8N3iC9cBhV/ZeejF3PmeZYQGj4GUGM3fgBfZEkjlBwGIC2UNUAfIHO2nBYUPG/y2AY+4bq3llrlAlQi9C8WSAlCKNI5suAizedPiMMlvUnR68votiSpek2HyWriJWcq6g7fXZ4iDHe0pY8krXfMrKMCzEvtECTWyXsHAzO/XYDulEf+7duxpnaKlQT9x8auvkVBpEaMoUn+Ep47L+1w0kyOCkXr03dLVaL2emMFxDhcqEG67MCvNQ/8wH1Apa2DRfdCcUrAgMBAAECggEBAJz4MBAwrdks3Vo9ZVHveqxiHl23dSilMnrW/suy8DcVo2S0OqQViDHFVPEiQFkAfJfku+JzU5IVYdVmkdhHcEXFpGmtBTpa9Fw31mp68F6l/op8EMRe9TE8t6gIo+qMDdS/nPeW6ggmZ36UvJjBqdAqqF8y3XM/4Or6CFMJkPU/gBTmvOGsMOLr4yxJ6dJMjEHRM8aHiQD105Xe49wFG7GtDNl8IsxjJihfR0whb8vSaeXKj7kazfjgj0cEnGz8iIp3Kw4OukuYsMpJ+ZPQl6I9YSFiW27Vi+011ZGxd2S7RWHt/ili6EsNstfMxNQIwd0Jtscf0RFBIfc/Hg87XzECgYEA9t7kbBEejTLkaKkpSCXKUtsZCGbYG6VYX1LoPdWtsQZwQRRIziskPf7RZMAhiDPSm3AXCyucBLPwTmdtRzC61XT8jRwmqdk4m1rbLYK/czk5TXEoUAmIYMjeBsXeG8v2C8bYfU/6kZSvs9p4czZBABiiuJXaYsCmJ+A7aqMrLRUCgYEA8uEModYLxtyYdba7CY88KdKQExaHflvB+uK8WmAp+Zs3FcmWl0fG4jb1ywUQF/+EZvJB2Iq/GgBFp8svp5kmJ+l+ksSCMDOponjDCcBPd2Nl6VPqy9u9CpgRmSd/03bQ2e+0JO00XzGqZ0/KERZmzBtDG149jNyeEQpizI7gOT8CgYEAl5wbPCLnWF/A1mXM7HoI3wmfPgGrBo9szl3kMtVfbjA+EDmc3MCx6UDs56r27OammL8l575IerrnAb+S5P2QQDcwQpjfRcAZe484u6JoYSLrhhvQXhb8ojO55v7tgLSpzmG34n2TrIRbw2CQSHExShXXGPUuwSb+485Zrwu2IGECgYEAqhYOKZti/e1n2y+PRf+Hy2YIvUVOt598dbyo2MV1P7aB2gElM2XxkmOYt4chIR0wVIOctw9bCtNb9EinY8AtZ0/t8swou6bCSeQ1+bMyM1JpgP/icsa8WRnrYQy3SJhxY92okx+GSI/YXKcUw+ijLpZ85UKW6flpvFdAny4DOjMCgYBM1goyt6NDBvcTWq3/500ex0KCkv29gv21ftsUwsOm8oRIWlx2x8DThbXrF3YvpnpUWTkkckUFs82WgX3PjWNlxdPBGOLkKA/gvyLAUWzkE3VY+c9ksJJGv1we557Kl7qSAOmk/6fjMYgstAp4MatWh2YY+0/sfyUBinzOhtofRw==",//商户私钥
                "json",//数据格式  {key:value,key:value...}
                "utf-8",//编码集
                "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAx+n+pEqTVi27mtj3CuUQXi2ixqeeTwE/0tGrW+sg6xtfajvJV67GYf2zzNxxBV0TYfhdbi70VI3DftEijg7GSNKoOilAu2DKQFqidnSxmN1Es1oRTaiaehqm1Uzs2uswpzBVR21iygLHujwthC8kNkMgxVFkjbE/qTn7z5wlsailtg6wF+hY3BcDCiaLyVLjEDngmrLyLXPLenjAuvXq20h9zV7CW9HXuhpPBDfsn4fv5TjgEl1smjJNr4O/VxICKDNPsvrCyNXhfroK9PEFFwH+4IWGeBUJAP2cSufNU0OA+UH+2xQnaR8Cz30QIgIslckBGuXQZvxqaY2mMMz14QIDAQAB",//支付宝公钥
                "RSA2");//非对称加密算法 RSA RSA2

        //网页支付的请求对象
        AlipayTradePagePayRequest alipayRequest =  new  AlipayTradePagePayRequest(); //创建API对应的request
        alipayRequest.setReturnUrl( "http://www.baidu.com" );//同步请求
        alipayRequest.setNotifyUrl( "http://localhost:8080/pay/result" );//异步请求
        //支付的请求参数
        alipayRequest.setBizContent( "{"  +
                "    \"out_trade_no\":\"" + order.getOrderId() + "\","  +
                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\","  +
                "    \"total_amount\":" + order.getMoney().doubleValue() + ","  +
                "    \"subject\":\"欢乐豆" + order.getBeanNumber() + "个\""  +
                "  }" ); //填充业务参数
        String form= "" ;
        try  {
            //发送支付请求（调用支付宝服务器），返回一个支付的html页面
            form = alipayClient.pageExecute(alipayRequest).getBody();
        }  catch  (AlipayApiException e) {
            e.printStackTrace();
        }
        response.setContentType( "text/html;charset=utf-8");
        response.getWriter().write(form); //直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();
    }

    /**
     * 支付交易查询接口
     */
    @RequestMapping("/pay/query")
    public int payResult(String orderid) throws AlipayApiException {
        //调用支付宝进行支付
        AlipayClient alipayClient =  new DefaultAlipayClient(
                "https://openapi.alipaydev.com/gateway.do",//沙箱环境的地址
                "2016073000127352",//APPID
                "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDqN7oDbnZUY66s48aYzhOVP+KHssz0WFT05kJYHSpWpVWceFflVGkAoHCZE00PbVcvZMAaYwzFzVCT9A8N3iC9cBhV/ZeejF3PmeZYQGj4GUGM3fgBfZEkjlBwGIC2UNUAfIHO2nBYUPG/y2AY+4bq3llrlAl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y+PRf+Hy2YIvUVOt598dbyo2MV1P7aB2gElM2XxkmOYt4chIR0wVIOctw9bCtNb9EinY8AtZ0/t8swou6bCSeQ1+bMyM1JpgP/icsa8WRnrYQy3SJhxY92okx+GSI/YXKcUw+ijLpZ85UKW6flpvFdAny4DOjMCgYBM1goyt6NDBvcTWq3/500ex0KCkv29gv21ftsUwsOm8oRIWlx2x8DThbXrF3YvpnpUWTkkckUFs82WgX3PjWNlxdPBGOLkKA/gvyLAUWzkE3VY+c9ksJJGv1we557Kl7qSAOmk/6fjMYgstAp4MatWh2YY+0/sfyUBinzOhtofRw==",//商户私钥
                "json",//数据格式  {key:value,key:value...}
                "utf-8",//编码集
                "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAx+n+pEqTVi27mtj3CuUQXi2ixqeeTwE/0tGrW+sg6xtfajvJV67GYf2zzNxxBV0TYfhdbi70VI3DftEijg7GSNKoOilAu2DKQFqidnSxmN1Es1oRTaiaehqm1Uzs2uswpzBVR21iygLHujwthC8kNkMgxVFkjbE/qTn7z5wlsailtg6wF+hY3BcDCiaLyVLjEDngmrLyLXPLenjAuvXq20h9zV7CW9HXuhpPBDfsn4fv5TjgEl1smjJNr4O/VxICKDNPsvrCyNXhfroK9PEFFwH+4IWGeBUJAP2cSufNU0OA+UH+2xQnaR8Cz30QIgIslckBGuXQZvxqaY2mMMz14QIDAQAB",//支付宝公钥
                "RSA2");//非对称加密算法 RSA RSA2

        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderid);
        request.setBizContent(bizContent.toString());
        AlipayTradeQueryResponse response = alipayClient.execute(request);
        if(response.isSuccess()){
            System.out.println("调用成功");

            //判断支付的结果
            String tradeStatus = response.getTradeStatus();
            if (tradeStatus.equals("TRADE_SUCCESS")) {
                //支付成功
                System.out.println("支付成功");

                //根据订单号 查询订单详情
                RechargeOrder order = rechargeOrderService.getByOrderId(orderid);

                //修改订单状态
                rechargeOrderService.updateOrderStatus(orderid, 1);

                //生成积分流水记录
                HappyBeanHistory happyBeanHistory = new HappyBeanHistory();
                happyBeanHistory.setuId(order.getuId());//欢乐豆流水所属用户
                happyBeanHistory.setBeanNumber(order.getBeanNumber());//欢乐豆的数量
                happyBeanHistory.setType(0);//增加
                happyBeanHistory.setSource(0);//欢乐豆来源 - 充值
                happyBeanHistory.setCreateTime(new Date());
                happyBeanHistoryService.insertHistory(happyBeanHistory);

                //给用户设置欢乐豆
                int newHappyBean = userService.addHappyBean(order.getuId(), order.getBeanNumber());
                //将最新的欢乐豆数量返回给前端
                return newHappyBean;
            }
        } else {
            System.out.println("调用失败");
        }

        return -1;
    }
}
